package com.lw.smartdevice.websocket.handler;

import com.lw.smartdevice.events.PowerCommandEvent;
import com.lw.smartdevice.exceptions.MyErrorCode;
import com.lw.smartdevice.exceptions.QueryMyBaseException;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/24 22:15
 *
 * 对设备进行电源控制的websocket,主要是给继电器设备进行命令发送的
 */
@Component
public class PowerCommandHandler extends BaseCommandHandler {


    /**
     * 监听发送命令的事件
     */
    @EventListener
    public void onEvent(PowerCommandEvent event){
        System.err.println("电源控制器发送命令");
        String deviceId = event.getDeviceId();
        String command = event.getCommand();
        //获取到会话
        WebSocketSession webSocketSession = getAllClients().get(deviceId);
        Assert.isTrue(webSocketSession!=null&&webSocketSession.isOpen(),()->{
            throw new QueryMyBaseException("设备不在线", MyErrorCode.DEVICE_OFFLINE);
        });
        try {
            webSocketSession.sendMessage(new TextMessage(command));//给设备发送命令
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
